﻿using System.Data;
using System.Diagnostics;

namespace Jayrock.Json.Conversion.Converters
{
    internal sealed class DataTableV1Exporter : ExporterBase
    {
        public DataTableV1Exporter() : base(typeof(DataTable)) { }

        protected override void ExportValue(ExportContext context, object value, JsonWriter writer)
        {
            Debug.Assert(value != null);
            Debug.Assert(writer != null);

            ExportDataTable(context, value as DataTable, writer);
        }

        private void ExportDataTable(ExportContext context, DataTable dt, JsonWriter writer)
        {
            writer.WriteStartObject();

            writer.WriteMember("tablename");
            context.Export(dt.TableName, writer);

            writer.WriteMember("total");
            context.Export(dt.Rows.Count, writer);

            writer.WriteMember("columns");
            writer.WriteStartArray();
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                writer.WriteString(dt.Columns[i].ColumnName);
            }
            writer.WriteEndArray();

            writer.WriteMember("rows");
            writer.WriteStartArray();
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                writer.WriteStartObject();
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    writer.WriteMember(dt.Columns[j].ColumnName);
                    context.Export(dt.Rows[i][j], writer);
                }
                writer.WriteEndObject();
            }
            writer.WriteEndArray();
            writer.WriteEndObject();
        }
    }
}
